package com.briup.labs.service.impl;

import com.briup.labs.mapper.SysRoleMapper;
import com.briup.labs.pojo.PageBean;
import com.briup.labs.pojo.Result;
import com.briup.labs.pojo.SysRole;
import com.briup.labs.pojo.SysUserRole;
import com.briup.labs.service.SysRoleService;
import com.briup.labs.util.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public List<SysRole> all() {
        return sysRoleMapper.all();
    }

    @Override
    public PageBean<SysRole> list(String pageNum, String pageSize, String key) {
        //创建PageBean对象
        PageBean<SysRole> pageBean = new PageBean<>();

        //检测数据输入格式
        int PN = 0;
        int PS = 0;
        try {
            PN = Integer.parseInt(pageNum);
            PS = Integer.parseInt(pageSize);
        } catch (Exception e) {
            pageBean.setTotal(null);
            pageBean.setItems(null);
            return pageBean;
        }

        //开启分页查询 PageHelper
        PageHelper.startPage(PN, PS);

        //调用mapper
        List<SysRole> sysRoles = sysRoleMapper.list(key);

        //Page中提供了方法，可以获取PageHelper分页查询后，得到的总记录条数和当夜数据
        Page<SysRole> page = (Page<SysRole>) sysRoles;

        //把数据填充到PageBean对象中
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return pageBean;
    }

    @Override
    public void saveOrUpdate(SysRole sysRole) {
        if (sysRole.getRoleId() == null) {
            //添加
            SysUserRole sysUserRole = new SysUserRole();
            sysRoleMapper.add(sysRole);
            sysUserRole.setUserId(sysRole.getCreateUserId());
            sysUserRole.setRoleId(sysRole.getRoleId());
            //sysRoleMapper.addBridgeUser(sysUserRole);
        } else {
            //修改
            sysRoleMapper.update(sysRole);
        }
    }

    @Override
    public void delete(Integer id) {
        //删除role表中的数据
        sysRoleMapper.delete(id);
        //删除role-user桥表中的数据
        sysRoleMapper.deleteBridgeUser(id);
    }
}